package itsm.isperp.module.controller.sparepart;

import itsm.isperp.framework.collection.tree.ITreeNode;
import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.data.domain.PageResponse;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.utils.HibernateUUIDGenerator;
import itsm.isperp.framework.utils.TreeNodeUtils;
import itsm.isperp.framework.web.controller.BaseController;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.framework.web.response.ResultMessage;
import itsm.isperp.module.entity.configuration.ConfCategory;
import itsm.isperp.module.entity.project.ProjProject;
import itsm.isperp.module.entity.sparepart.SptSparepart;
import itsm.isperp.module.entity.sparepart.SptSparepartMinStockRule;
import itsm.isperp.module.entity.sparepart.SptSparepartRelation;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.configuration.ConfCategoryService;
import itsm.isperp.module.service.configuration.ConfCiService;
import itsm.isperp.module.service.customer.CusCustomerService;
import itsm.isperp.module.service.project.ProjProjectService;
import itsm.isperp.module.service.provider.PrdProviderService;
import itsm.isperp.module.service.sparepart.SptSparepartCategoryService;
import itsm.isperp.module.service.sparepart.SptSparepartChangeDetailService;
import itsm.isperp.module.service.sparepart.SptSparepartInDetailService;
import itsm.isperp.module.service.sparepart.SptSparepartRelationService;
import itsm.isperp.module.service.sparepart.SptSparepartService;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 备件管理控制器
 * 
 * @author lizx
 * @date 2013-9-12
 */
@Controller
@RequestMapping("sparepart/sparepart")
public class SptSparepartController extends BaseController<SptSparepart> {

	@Autowired
	protected SptSparepartService sptSparepartService;

	@Autowired
	protected SptSparepartCategoryService sptSparepartCategoryService;

	@Autowired
	protected SptSparepartInDetailService sptSparepartInDetailService;

	@Autowired
	protected SptSparepartChangeDetailService sptSparepartChangeDetailService;
	
	@Autowired
  protected ProjProjectService projProjectService;
	
	@Autowired
  protected PrdProviderService prdProviderService;

	@Override
	public SptSparepartService getService() {
		return sptSparepartService;
	}

	@Override
	public String getPageTitle() {
		return "备件管理";
	}

	@RequestMapping("/getConfCategorys")
	@ResponseBody
	public List<? extends ITreeNode> getConfCategorys(String sparepartId) {

		List<SptSparepartMinStockRule> list = sptSparepartService
				.getSparepartMinStockRule(sparepartId);

		ConfCategoryService confCategoryService = ContextHolder
				.getSpringBean("confCategoryService");

		List<ConfCategory> confCategorys = confCategoryService.findAll(
				new JqGridRequest().isPageable(false)).getContent();

		Set<String> set = new HashSet<String>();
		for (SptSparepartMinStockRule r : list)
			set.add(r.getConfCategoryId());

		for (ConfCategory c : confCategorys) {
			if (set.contains(c.getId())) {
				c.setChecked(true);
			}
		}
		List<ConfCategory> tree = TreeNodeUtils.parseFormList(confCategorys);

		return tree;
	}

	@RequestMapping("listDetail")
	@ResponseBody
	public PageResponse<Map<String, Object>> listDetail(JqGridRequest request,
			HttpServletRequest req) {
		String ty = req.getParameter("ty");
		String sourceId = req.getParameter("sourceId");
		String searchStr="";
		String term = req.getParameter("term");
		if(StringUtils.isNotBlank(ty))
		{
		  searchStr="id NOT IN(SELECT ci_id FROM spt_sparepart_relation WHERE STATUS=0 AND EXISTS(SELECT 1 FROM v_sparepart_all WHERE id=spt_sparepart_relation.sparepart_id and process_id is not null))";
		  if(ty.equals("sparepartBack"))
		  {
		    String cusUserName=req.getParameter("cusUserName");
		    searchStr+=" and support_staff_id='"+cusUserName+"'";
		  }
		  request.setSearchString(searchStr);
		}
		if (StringUtils.isNotEmpty(term)) {
		      request.isPageable(false);
		      request.setRows(15);
		      request.setSelectColumns("id", "code", "name", "sn");
		      request.setSearchString("  name LIKE '%" + term + "%' OR   code LIKE '%"
		          + term + "%' OR  sn LIKE '%" + term + "%'");
		      return this.getService().findAllDetailByRequest(request);
		    }
		
		request.addFilterRule("use_status", JqGridFilterRuleOp.eq, "1");
		request.setSort("code", Direction.ASC);
		return this.getService().findAllDetailByRequest(request);

	}
	
	@RequestMapping("listSparepartAllList")
	@ResponseBody
	public PageResponse<Map<String, Object>> listSparepartAllList(JqGridRequest request,
			HttpServletRequest req) {

		return this.getService().findSparepartAllList(request);

	}
	
	@RequestMapping(value = { "sptAllProcessManage", "" })
	public ModelAndView sptAllProcessManage(HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		ProjProjectService projProjectService = ContextHolder
				.getSpringBean("projProjectService");
		mv.addObject("projects",
				projProjectService.findAllPublished("id", "name"));
		return mv;
	}
	
	@RequestMapping(value = { "sptAllProcessEditManage", "" })
	public ModelAndView sptAllProcessEditManage(HttpServletRequest req) {
		ModelAndView mv = this.getModelAndView();
		ProjProjectService projProjectService = ContextHolder
				.getSpringBean("projProjectService");
		String userName=ContextHolder.getLoginUsername();
    mv.addObject("curUserName", userName);
		mv.addObject("projects",
				projProjectService.findAllPublished("id", "name"));
		return mv;
	}

	@Override
	@RequestMapping("edit")
	public ModelAndView edit(String id, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = new ModelAndView("sparepart/sparepart/edit");

		String categoryId = req.getParameter("categoryId");
		
		String categoryName = "";
		SptSparepart model = null;
		if (StringUtils.isEmpty(id)) {
			model = new SptSparepart();
			model.setId(HibernateUUIDGenerator.generate());
			
			IUser u=ContextHolder.getLoginUser();
			
			model.setUseStaffId(u.getUsername());
			model.setUseStaffName(u.getFullname());
			
			if (StringUtils.isNotEmpty(categoryId)) {
				model.setSptSparepartCategoryId(categoryId);
				categoryName = this.sptSparepartCategoryService.findOne(
						categoryId).getName();
			}
			String providerId=req.getParameter("providerId");
      if(StringUtils.isNotBlank(providerId))
      {
        model.setManufacturerProviderId(providerId);
        model.setManufacturerProviderName(prdProviderService.findOne(providerId).getName());
      }
      model.setStockInDate(new Date());
        

		} else {
			model = this.getService().findOne(id);
			categoryName = this.sptSparepartCategoryService.findOne(
					model.getSptSparepartCategoryId()).getName();

		}
		
		
		String projectId=req.getParameter("projectId");
    if(StringUtils.isNotEmpty(projectId))
    {
      List<ProjProject> list=new ArrayList<ProjProject>();
      list.add(projProjectService.findOne(projectId));
      mv.addObject("projects",list
          );
    }else
    {
      mv.addObject("projects",
          projProjectService.findAllPublished("id", "name"));
    }
    String ty=req.getParameter("ty");
    if(StringUtils.isNotBlank(ty))
    {
      mv.addObject("ty", ty);
      String sourceId=req.getParameter("sourceId");
      mv.addObject("sourceId", sourceId);
      if(ty.equals("sparepartIn"))
      {
        model.setStatus("已入库");
      }
    }

		mv.addObject("categoryName", categoryName);

		mv.addObject("model", model);

		return mv;
	}

	@RequestMapping("save")
	@ResponseBody
	public ResultMessage save(SptSparepart model, HttpServletRequest req) {
	  
		String ty=req.getParameter("ty");
		Integer useStatus=1;
		if(StringUtils.isNotBlank(ty) && ty.equals("sparepartIn"))
    {
      SptSparepartRelationService sptSparepartRelationService = ContextHolder
          .getSpringBean("sptSparepartRelationService");
      String sourceId = req.getParameter("sourceId");
      SptSparepartRelation sptRelation=new SptSparepartRelation();
      sptRelation.setSparepartId(sourceId);
      sptRelation.setCiId(model.getCode());
      sptRelation.setStatus(0);
      sptRelation.setTypeKey("sparepartIn");
      sptSparepartRelationService.saveOrUpdate(sptRelation);
      useStatus=0;
    }
		model.setId(model.getCode());
		if(StringUtils.isNotBlank(model.getProjectId()))
		{
		  String projectName=projProjectService.findOne(model.getProjectId()).getName();
		  model.setProjectName(projectName);
		  
		}
		model.setUseStatus(useStatus);
    this.getService().saveOrUpdateAndSpecific(model, req);
		return ResultMessage.newInstance(true, null, model.getId());
	}

	@RequestMapping("search")
	public ModelAndView search(JqGridRequest request, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = new ModelAndView("sparepart/sparepart/search");
		CusCustomerService cusCustomerService = ContextHolder
				.getSpringBean("cusCustomerService");
		mv.addObject("customerCiCounts",
				cusCustomerService.getCustomerCiCount());

		AppDictService appDictService = ContextHolder
				.getSpringBean("appDictService");
		mv.addObject("var_assetStatus", appDictService.findByType("CI_STATUS"));

		mv.addObject("customerId",cusCustomerService.getCompanyCustomer().getId());

		return mv;
	}

	@RequestMapping("viewEdit")
	public ModelAndView viewEdit(String id, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = new ModelAndView("sparepart/sparepart/viewEdit");

		JqGridRequest request = new JqGridRequest();
		request.addFilterRule("id", JqGridFilterRuleOp.eq, id);
		List<Map<String, Object>> list = sptSparepartService
				.findAllDetailByRequest(request).getContent();
		if (list != null && list.size() > 0) {
			mv.addObject("model", list.get(0));
		} else {
			mv.addObject("model", null);
		}

		return mv;
	}
	
	@RequestMapping("viewSptEdit")
	public String viewSptEdit(String id, HttpServletRequest req, RedirectAttributes redirectAttributes)
			throws Exception {
		
		JdbcTemplate jdbcTemplate = ContextHolder
				.getSpringBean("jdbcTemplate");
		String sql="select * from v_spt_process where id='"+id+"'";
		List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
		String url="";
		if(list.size()>0)
		{
			String type=list.get(0).get("spt_type").toString();
			switch(type)
			{
			case "备件归还":
				url="/sparepart/sparepartBack/old/view";
				break;
			case "备件报废":
				url="/sparepart/sparepartDiscard/old/view";
				break;
			case "备件采购":
				url="/sparepart/sparepartIn/old/view";
				break;
			case "备件领用":
				url="/sparepart/sparepartOut/old/view";
				break;
			default:
			}
			
		}
		
		redirectAttributes.addAttribute("id", id);
		return "redirect:"+url;
	}
	
	@RequestMapping("deleteSptEdit")
	public ResultMessage deleteSptEdit(String id,String sparepartId, HttpServletRequest req)
	{
	  JdbcTemplate jdbcTemplate = ContextHolder
        .getSpringBean("jdbcTemplate");
    String sql="select * from v_spt_process where id='"+id+"'";
    String deleteSql="";
    List<Map<String,Object>> list=jdbcTemplate.queryForList(sql);
    String url="";
    if(list.size()>0)
    {
      String type=list.get(0).get("spt_type").toString();
      switch(type)
      {
      case "备件归还":
        deleteSql="delete from spt_sparepart_back where id='"+id+"'";
        break;
      case "备件报废":
        deleteSql="delete from spt_sparepart_discard where id='"+id+"'";
        break;
      case "备件采购":
        deleteSql="delete from spt_sparepart_in where id='"+id+"'";
        break;
      case "备件领用":
        deleteSql="delete from spt_sparepart_out where id='"+id+"'";
        break;
      default:
      }
      jdbcTemplate.update(deleteSql);
      
    }
    return ResultMessage.newInstance(true);
	  
	}
	
	

	@RequestMapping("inOutList")
	public ModelAndView inOutList(String sparepartId, HttpServletRequest req)
			throws Exception {
		ModelAndView mv = this.getModelAndView();

		mv.addObject("id", sparepartId);
		return mv;
	}

	@RequestMapping("projectUsed")
	@ResponseBody
	public PageResponse<Map<String, Object>> projectUsed(String sparepartId,
			JqGridRequest request, HttpServletRequest req) {
		return sptSparepartService.findAllProjectUsedByRequest(sparepartId,
				request);
	}

	@RequestMapping("updateStore")
	@ResponseBody
	public ResultMessage updateStore(JqGridRequest request,
			HttpServletRequest req) {
		return sptSparepartService.updateStore();
	}
	
	@Override
	@RequestMapping(value = { "manage", "" })
	public ModelAndView manage(HttpServletRequest req) {

		CusCustomerService cusCustomerService = ContextHolder
				.getSpringBean("cusCustomerService");
		ModelAndView mv = this.getModelAndView();
		mv.addObject("customerCiCounts",
				cusCustomerService.getCustomerCiCount());
 
		AppDictService appDictService = ContextHolder
				.getSpringBean("appDictService");
		mv.addObject("var_assetStatus", appDictService.findByType("CI_STATUS"));
		
		

		return mv;
	}
	
	@RequestMapping("autocompleteSpeclist")
	@ResponseBody
	public List<Map<String,Object>> autocompleteSpeclist(JqGridRequest request, HttpServletRequest req) {
		String categoryId=req.getParameter("categoryId");
		String term = req.getParameter("term");
		List<Map<String,Object>> result=null;
		ConfCiService confCiService = ContextHolder
				.getSpringBean("confCiService");
		request.addFilterRule("are_company", JqGridFilterRuleOp.eq, "1");
		if (StringUtils.isNotEmpty(term)) {
			request.isPageable(false);
			request.setRows(10);
			request.setSearchString("  specification LIKE '%" + term + "%' OR   model LIKE '%" + term.toUpperCase() + "%' ");
		} 
		if(StringUtils.isNotEmpty(categoryId))
		{
			request.addFilterRule("conf_category_id", JqGridFilterRuleOp.eq, categoryId);
		}
		result=confCiService.listSepAndModel(request);

	    return result;

	}

}
